package com.cx.controller.admin.basic;

import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController("admin/basic/readfile")
@RequestMapping("admin/basic/readfile")
public class ReadFileController {

    //读图片
    @GetMapping("/image/**")
    public String image(HttpServletRequest request,HttpServletResponse response) throws Exception {

        String servletPath = request.getServletPath();
		String name = servletPath.replaceFirst("/admin/basic/readfile/", "");
		
		InputStream stream = getClass().getClassLoader().getResourceAsStream(name);
        
        ServletOutputStream out = null;
		try {
			String imageExt = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
			response.setContentType("image/"+imageExt);
			out = response.getOutputStream();
			//读取文件流
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = stream.read(buffer)) != -1){
				out.write(buffer,0,len);
			}
			
			out.flush();
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			out.close();
			stream.close();
		}
		return null;
    }
    
    //读图片
    @GetMapping("/template/**")
    public String template(HttpServletRequest request,HttpServletResponse response) throws Exception {

        String servletPath = request.getServletPath();
		String name = servletPath.replaceFirst("/admin/basic/readfile/", "");
		
		InputStream stream = getClass().getClassLoader().getResourceAsStream(name);
        
        ServletOutputStream out = null;
		try {
			response.setContentType("application/vnd.ms-excel");
			out = response.getOutputStream();
			//读取文件流
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = stream.read(buffer)) != -1){
				out.write(buffer,0,len);
			}
			
			out.flush();
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			out.close();
			stream.close();
		}
		return null;
    }
}
